<template>
	<div>
		<el-dialog :title="title + '广告图'" style="z-index: 999;" :modal-append-to-body="false" :visible.sync="isShow" :close-on-click-modal="false" :before-close="close" width="1200px">
			<div class="form-box">
				<el-form ref="form" :model="form" :rules="rules" label-width="110px">
					<el-row>
						<el-col :span="12">
							<el-form-item label="广告图片" prop="imageUrl">
								<el-upload
									ref="upload"
									:class="{'upload-cover-disabled': form.imageUrl}"
									list-type="picture-card"
									:file-list="fileList"
									:limit="1"
									:accept="'image/*'"
									:headers="headerParams"
									:action="getUploadUrl()"
									:on-progress="handleProgress"
									:on-success="handleSuccess"
									:on-error="handleError"
									:on-remove="handleRemove"
									:disabled="isUploading"
								>
									<i class="el-icon-plus avatar-uploader-icon" slot="default" ></i>
								</el-upload>
								
								<el-alert class="upload-progress" type="warning" title="" v-if="isUploading">
									<template slot="title">
										<div class="upload-progress-text">
											<i class="el-icon-loading"></i>
											<span>上传中，请勿关闭窗口!</span>
										</div>
									</template>
								</el-alert>
								<el-alert class="upload-progress" type="success" title="上传成功!" show-icon v-if="isUploadingSuccess"></el-alert>
							</el-form-item>
						</el-col>
					</el-row>
					
					<el-row>
						<el-col :span="12">
							<el-form-item label="广告标题" prop="title">
								<el-input v-model="form.title" placeholder="请填写广告标题"></el-input>
							</el-form-item>
						</el-col>
						
						<el-col :span="12">
							<el-form-item label="广告排序" prop="sort">
								<el-input v-model.number="form.sort" placeholder="请填写排序序号" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					
					<el-row>
						<el-col :span="24">
							<el-form-item label="点击广告跳转" prop="targetType">
								<el-radio v-model="form.targetType" label="0" @change="changetype">默认页面</el-radio>
								<el-radio v-model="form.targetType" label="1" @change="changetype">指定页面（小程序内）</el-radio>
								<el-radio v-model="form.targetType" label="4" @change="changetype">专题页面</el-radio>
								<el-radio v-model="form.targetType" label="2" @change="changetype">公众号文章</el-radio>
								<el-radio v-model="form.targetType" label="3" @change="changetype">外部小程序</el-radio>
							</el-form-item>
						</el-col>
					</el-row>
					<!-- 默认页面 -->
					<el-row v-if="form.targetType == '0'">
						<el-col :span="24">
							<el-form-item label="广告内容" prop="content">
								<d2-ueditor v-model="form.content"></d2-ueditor>
							</el-form-item>
						</el-col>
					</el-row>
					<!-- 指定页面（小程序内） -->
					<el-row v-if="form.targetType == '1'">
						<el-col :span="12">
							<el-form-item label="跳转路由地址" prop="frontRoutePath">
								<el-input v-model="form.frontRoutePath" placeholder="请填写跳转页面的路由地址" clearable></el-input>
							</el-form-item>
						</el-col>
						
						<el-col :span="12">
							<el-form-item label="接口地址" prop="apiUrl">
								<el-input v-model="form.apiUrl" placeholder="请填写接口地址，没有可以不填" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<!-- 公众号文章 -->
					<el-row v-if="form.targetType == '2'">
						<el-col :span="24">
							<el-form-item label="公众号链接" prop="content">
								<el-input v-model="form.content" placeholder="请填写公众号文章链接" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<!-- 外部小程序 -->
					<el-row v-if="form.targetType == '3'">
						<el-col :span="12">
							<el-form-item label="小程序APPID" prop="apiUrl">
								<el-input v-model="form.apiUrl" placeholder="请填写跳转小程序的APPID" clearable></el-input>
							</el-form-item>
						</el-col>
						
						<el-col :span="12">
							<el-form-item label="跳转页面地址" prop="frontRoutePath">
								<el-input v-model="form.frontRoutePath" placeholder="请填写跳转小程序的页面地址，如果为首页可以不填" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<!-- 专题页面 -->
					<el-row v-if="form.targetType == '4'">
						<el-col :span="24">
							<el-form-item label="指定专题" prop="frontRoutePath">
								<el-input v-model="form.frontRoutePath" placeholder="请点击按钮选择专题" readonly>
									<el-button slot="append" @click="openSpecialPage">点击选择</el-button>
								</el-input>
							</el-form-item>
						</el-col>
					</el-row>
					
					<el-row v-if="isEdit">
						<el-col :span="24">
							<el-form-item label="状态" prop="adStatus">
								<el-radio v-model="form.adStatus" label="1">上架</el-radio>
								<el-radio v-model="form.adStatus" label="0">下架</el-radio>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
			
			<div slot="footer">
				<el-button type="primary" @click="submit">保 存</el-button>
				<el-button @click="reset" v-if="!isEdit">重 置</el-button>
				<el-button @click="close">取 消</el-button>
			</div>
		</el-dialog>
		
		<el-dialog title="选择专题页面" style="z-index: 999;" :modal-append-to-body="false" :visible.sync="showSpecialPage" :close-on-click-modal="false" :before-close="closeSpecialPage" width="1100px">
			<el-table :data="tableData" stripe border style="width: 100%">
				<el-table-column type="index" fixed label="序号" width="60" align="center"></el-table-column>
				
				<el-table-column prop="skuThumbImage" label="页面头图" width="110" align="center">
					<template slot-scope="scope">
						<el-image style="width: 80px; height: 35px" :src="scope.row.posterUrl" fit="cover" :preview-src-list="[scope.row.posterUrl]"></el-image>
					</template>
				</el-table-column>
				
				<el-table-column prop="title" label="标题"></el-table-column>
				<el-table-column prop="sort" label="排序" width="60" align="center"></el-table-column>
				
				<el-table-column label="开始时间" :formatter="forDate" prop="startTime" width="150" align="center"></el-table-column>
				<el-table-column label="结束时间" :formatter="forDate" prop="endTime" width="150" align="center"></el-table-column>
				
				<el-table-column label="发布状态" prop="publishStatus" width="90" align="center">
					<template slot-scope="scope">
						<el-tag type="success" size="mini" v-if="scope.row.publishStatus == 1">上架中</el-tag>
						<el-tag type="warning" size="mini" v-if="scope.row.publishStatus == 0">已下架</el-tag>
					</template>
				</el-table-column>
				
				<el-table-column label="操作" width="100" align="center" fixed="right">
					<template slot-scope="scope">
						<el-button type="info" size="mini" disabled v-if="scope.row.id == form.apiUrl">已选</el-button>
						<el-button type="primary" size="mini" @click="chooseSpecialPage(scope.row)" v-else>选择</el-button>
					</template>
				</el-table-column>
			</el-table>
			
			<div class="page">
				<el-pagination
					background
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					layout="total, prev, pager, next"
					:total="total"
				></el-pagination>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import dayjs from 'dayjs'
	import util from '@/libs/util'
	import { uploadImageUrl } from '@api/common/common'
	import { addCarousel, editCarousel, editCarouselDetail, getCarouselDetail } from '@api/platform/platformBanner'
	import { getSpecialPageList } from '@api/platform/platformMarketing'
	export default {
		props: {
			isShow: Boolean,
			isEdit: Boolean,
			item: Object,
		},
		data() {
			let validateImg = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请上传轮播图'));
				} else {
					callback();
				}
			}
			let validateRouteUrl = (rule, value, callback) => {
				if (value === '' && this.form.targetType == 1) {
					callback(new Error('请填写跳转页面的链接地址'));
				} else if (value === '' && this.form.targetType == 3) {
					callback(new Error('请填写跳转页面的链接地址'));
				} else if (value === '' && this.form.targetType == '4') {
					callback(new Error('请选择需要链接的专题页'));
				} else {
					callback();
				}
			}
			let validateApiUrl = (rule, value, callback) => {
				if (value === '' && this.form.targetType == 1) {
					callback(new Error('请填写接口地址'));
				} else if (value === '' && this.form.targetType == 3) {
					callback(new Error('请填写跳转小程序的APPID'));
				} else {
					callback();
				}
			}
			let validateContent = (rule, value, callback) => {
				if (value === '' && this.form.targetType == '0') {
					callback(new Error('请填写广告内容'));
				} else if (value === '' && this.form.targetType == '2') {
					callback(new Error('请填写公众号文章链接'));
				} else {
					callback();
				}
			}
			return {
				form: {
					title: '',
					sort: 0,
					imageUrl: '',
					moduleNo: 'index',
					districtCode: '0', //0全部城市可见
					targetType: '', //0默认的广告展示页 1小程序中的指定页面 2公众号链接 3外部小程序
					apiUrl: '',
					frontRoutePath: '',
					adStatus: '1',
					content: '',
				},
				rules: {
					title: [{ required: true, message: '请填写广告标题', trigger: 'blur' }],
					sort: [{ required: true, message: '请填写排序序号', trigger: 'blur' }, { type: 'number', message: '请填写正确的数字'}],
					imageUrl: [{required: true, validator: validateImg, trigger: 'blur'}],
					moduleNo: [{ required: true, message: '请选择广告展示位置', trigger: 'blur' }],
					districtCode: [{ required: true, message: '请选择广告所属城市', trigger: 'blur' }],
					targetType: [{ required: true, message: '请选择跳转类型', trigger: 'blur' }],
					frontRoutePath: [{required: true, validator: validateRouteUrl, trigger: 'blur'}],
					// apiUrl: [{required: true, validator: validateApiUrl, trigger: 'blur'}],
					adStatus: [{ required: true, message: '请选择状态', trigger: 'blur' }],
					content: [{required: true, validator: validateContent, trigger: 'blur'}],
				},
				
				headerParams: { // 上传图片的请求头
					clientId: '',
					democracy: ''
				},
				fileList: [],
				isUploading: false,
				isUploadingSuccess: false,
				
				showSpecialPage: false,
				specialPage: '',
				tableData: [],
				currentPage: 1,
				pageSize: 10,
				total: 0,
			}
		},
		computed: {
			title() {
				let text = '';
				if(this.isEdit) {
					text = '编辑'
				} else {
					text = '添加'
				}
				return text;
			},
		},
		watch: {
			isShow(val) {
				if(val) {
					if(this.isEdit) {
						this.initForm();
					}
				}
			},
			'form.imageUrl': {
				handler(val) {
					if(val) {
						this.$refs['form'].clearValidate('imageUrl');
					}
				},
				deep: true
			},
		},
		methods: {
			initForm() { //初始化数据
				this.form.title = this.item.title;
				this.form.sort = this.item.sort;
				this.form.imageUrl = this.item.imageUrl;
				this.form.targetType = this.item.targetType.toString();
				this.form.apiUrl = this.item.apiUrl;
				this.form.frontRoutePath = this.item.frontRoutePath;
				this.form.adStatus = this.item.adStatus.toString();
				
				if(this.item.imageUrl) {
					this.fileList.push({
						name: 'ads.jpg',
						url: this.item.imageUrl
					});
				}
				
				getCarouselDetail({adId: this.item.id})
					.then(res => {
						this.form.content = res.data.content;
					})
			},
			
			changetype(val) { //选择广告跳转类型
				if(val != '1') {
					this.form.frontRoutePath = '';
					this.form.apiUrl = '';
				} else {
					this.form.content = '';
				}
			},
			
			//上传图片组件
			getUploadUrl () {
				return uploadImageUrl();
			},
			handleProgress() {
				this.isUploading = true;
				this.isUploadingSuccess = false;
			},
			handleSuccess (response, file) {
				if (response.code == '000000') {
					this.$message.success('上传图片成功');
					this.form.imageUrl = response.data.url;
					this.isUploadingSuccess = true;
				} else {
					this.$message.error('上传图片失败:' + response.message);
					this.form.imageUrl = '';
					this.fileList.splice(0);
					this.isUploadingSuccess = false;
				}
				this.isUploading = false;
			},
			handleError (err, file) {
				console.log(err)
				this.$message.error('上传失败，请重新上传!');
				this.fileList.splice(0);
				this.isUploading = false
				this.isUploadingSuccess = false;;
			},
			handleRemove() {
				this.form.imageUrl = '';
				this.fileList = [];
				this.$refs.upload.clearFiles();
				
				this.isUploading = false;
				this.isUploadingSuccess = false;
			},
			
			// 选择专题弹窗
			openSpecialPage() {
				this.showSpecialPage = true;
				this.getSpecialPageList();
			},
			closeSpecialPage() {
				this.showSpecialPage = false;
			},
			getSpecialPageList() { //获取专题列表
				getSpecialPageList({
					publishStatus: 1,
					currentPage: this.currentPage,
					pageSize: this.pageSize
				})
					.then(res => {
						this.tableData = res.data.content;
						this.total = res.data.total;
					})
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getSpecialPageList();
			},
			forDate(row, column) { //时间格式化
				if(column.property == 'startTime') {
					return row.startTime == null ? '-' : dayjs(row.startTime).format('YYYY-MM-DD HH:mm:ss');
				}
				if(column.property == 'endTime') {
					return row.endTime == null ? '-' : dayjs(row.endTime).format('YYYY-MM-DD HH:mm:ss');
				}
			},
			chooseSpecialPage(item) { //选择指定专题
				this.form.apiUrl = item.id;
				this.form.frontRoutePath = item.title;
				this.showSpecialPage = false;
			},
			
			// 表单操作
			submit() { //提交添加or编辑
				this.$refs.form.validate(valid => {
					if (valid) {
						let params = this.objDeepCopy(this.form);
						delete params.content;
						
						if(this.isEdit) { //修改
							params.id = this.item.id;
							
							editCarousel(params)
								.then(() => {
									editCarouselDetail({
										adId: this.item.id,
										content: this.form.content
									})
										.then(() => {
											this.$message.success('轮播图修改成功！');
											this.close();
											
											this.$emit('submit');
										})
									
								})
						} else { //添加
							delete params.adStatus;
							
							addCarousel(params)
								.then(res => {
									editCarouselDetail({
										adId: res.data,
										content: this.form.content
									})
										.then(() => {
											this.$message.success('轮播图添加成功！');
											this.close();
											
											this.$emit('submit');
										})
								})
						}
					}
				})
			},
			reset() {
				this.$refs.form.resetFields();
				this.$refs.upload.clearFiles();
				this.fileList = [];
				this.isUploading = false;
				this.isUploadingSuccess = false;
				
				this.form.title = '';
				this.form.sort = 0;
				this.form.imageUrl = '';
				this.form.targetType = '';
				this.form.apiUrl = '';
				this.form.frontRoutePath = '';
				this.form.adStatus = '1';
				this.form.content = '';
				this.specialPage = '';
			},
			
			objDeepCopy (source) { //深拷贝
				let sourceCopy = source instanceof Array ? [] : {};
				for (let item in source) {
					sourceCopy[item] = typeof source[item] === 'object' ? this.objDeepCopy(source[item]) : source[item];
				}
				return sourceCopy;
			},
			
			close() {
				this.$emit('close');
				this.reset();
			}
		},
		mounted() {
			let client_id;
			let getId = util.cookies.get('client');
			let getId2_reverse = getId.substring(0, 6);
			let getId2 = getId2_reverse.split('').reverse().join(''); //后6位
			let getId1 = getId.substring(6, 13); //前7位
			client_id = getId1 + getId2;
			this.headerParams.clientId = 'client'+client_id; //请求头加client_id
			
			let democracy = util.cookies.get('democracy');
			this.headerParams.democracy = democracy; //请求头加token
		}
	}
</script>

<style lang="scss" scoped>
	.form-box {
		padding: 20px 30px;
	}
	
	.upload-cover-disabled {
		::v-deep .el-upload {
			display: none;
		}
	}
	
	::v-deep .el-alert__content {
		line-height: normal!important;
	}
	
	.el-table {
		::v-deep .el-table__cell {
			padding: 5px 0;
		}
	}
	.page {
		margin-top: 20px;
	}
</style>